package fun.xinnix.concurrent;

import cn.hutool.log.StaticLog;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadTest {
    private static int sum = 0;
    private static int count = 10;

    // 第一种方式, synchronized
    public synchronized void increase() {
        sum++;
    }

    // 第二种方式, lock
    ReentrantLock lock = new ReentrantLock(false);

    public void increase2() {
        lock.lock();
        Condition condition = lock.newCondition();
        try {
            sum++;
        } finally {
            lock.unlock();
        }
    }

    // 第三种方式,atomic
    private AtomicInteger inc = new AtomicInteger();

    public void increase3() {
        inc.getAndIncrement();
    }


    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                5,
                5,
                5,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(5), new ThreadPoolExecutor.CallerRunsPolicy());
//        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        ThreadTest threadTest = new ThreadTest();
        for (int i = 0; i < 5; i++) {
            threadPool.execute(() -> {
                for (int j = 0; j < 1500; j++) {
                    threadTest.increase3();
                }
            });
        }
        Thread.sleep(1500);
        StaticLog.info("{}", threadTest.inc);
        threadPool.shutdown();
    }
}
